package fda.main;

import java.util.LinkedList;
import java.util.List;

import fda.base.Constants;
import fda.base.DiskFile;
import fda.base.DiskFile2;
import fda.base.IOCounter;
import fda.join.ZigZagJoinEngine;
import fda.schema.Schema;
import fda.schema.TableInfo;

/**
 *	Use this start point to run Merge-Join operation
 */
public class MainJoinMerge {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// delete all files in folder when test starts
		DiskFile.clearAllFiles(Constants.PRE_SUB);

		////////////////////////////////////////////
		// read table description 
		////////////////////////////////////////////
		Schema schema = new Schema();
		schema.init(Constants.PRE_FILES + "schema.txt");
		List<TableInfo> sortedFiles = new LinkedList<TableInfo>();

		////////////////////////////////////////////
		// sort all tables and keep sorted files
		////////////////////////////////////////////
		for (TableInfo table : schema.getTables()) {

			// clear temp directory
			DiskFile.clearFiles(Constants.PRE_SUB, "merge");

			DiskFile source = new DiskFile(table);
			List<DiskFile> subLists = new LinkedList<DiskFile>();

			// sort in sublists
			Main.doSorting(subLists, source);

			// merge all sublists
			String mergedFile = Main.doMerging(subLists);

			// create a copy of TableInfo for merged file
			sortedFiles.add(new TableInfo(table, mergedFile));
		}

		System.out.print(String.format("\nTables sorted in: \n%s\n%s", sortedFiles.get(0), sortedFiles.get(1)));

		////////////////////////////////////////////
		// join two tables
		////////////////////////////////////////////

		DiskFile2 df1 = new DiskFile2(sortedFiles.get(0), true);
		DiskFile2 df2 = new DiskFile2(sortedFiles.get(1), true);

		// create new Table for Joined tables
		TableInfo tabInfoOut = Schema.joinTables(sortedFiles.get(0), sortedFiles.get(1), null);
		DiskFile2 diskOut = new DiskFile2(tabInfoOut, false);

		
		ZigZagJoinEngine zigZagJoin = new ZigZagJoinEngine(df1, df2, diskOut);
		zigZagJoin.join();

		Main.log("Join of tables ended");
		////////////////////////////////////////////
		// End of join
		////////////////////////////////////////////
		
		// print report about all operations
		IOCounter.getInst().printReport();
	}

}
